<?php

/**
 * Process requests from user submitted forms
 *
 * PHP version 5
 *
 * LICENSE: This source file is subject to the MIT License, available
 * at http://www.opensource.org/licenses/mit-license.html
 *
 * @author     Jayson Schmidt <jayson@888mobileapps.com>
 * @copyright  2013 888MobileApps
 * @license    http://www.opensource.org/licenses/mit-license.html
 */

/*
 * Enable sessions
 */
session_start();

/*
 * Include necessary config info
 */
include_once $_SERVER['DOCUMENT_ROOT'].'/workout/config/db-cred.inc.php';

/*
 * Define constants for config info
 */
foreach($C as $name=>$value) {
	define($name, $value);
}

if($_POST['submit'] == 'Delete Checked')
	$_POST['action'] = 'delete_item';

/*
 * Create a lookup array for form actions
 */
$actions = array(
			'create_exercise'=>array(
				'object'=>'Exercise_Builder',
				'method'=>'createExercise',
				'header'=>'Location: /workout/exercise_builder.php'
				),
			 'update_exercise'=>array(
			 	'object'=>'Exercise_Builder',
				'method'=>'updateExercise',
				'header'=>'Location: /workout/exercise_builder.php?exercise_id='.$_POST['exercise_id']
			   ),
			 'add_item'=>array(
			 	'object'=>'Exercise_Builder',
				'method'=>'addItem',
				'header'=>'Location: /workout/exercise_builder.php?exercise_id='.$_POST['exercise_id']
			   ),
			 'delete_item'=>array(
				'object'=>'Exercise_Builder',
				'method'=>'deleteItem',
				'header'=>'Location: /workout/exercise_builder.php?exercise_id='.$_POST['exercise_id']
			   ),
			 'user_login'=>array(
			 	'object'=>'Admin',
				'method'=>'processLoginForm',
				'header'=>'Location: /workout/exercise_builder.php'
				),
			  'user_logout'=>array(
			  	'object'=>'Admin',
				'method'=>'processLogout',
				'header'=>'Location: /workout/exercise_builder.php'
				)
			);
		
/*
 * Verify anti-CSRF token and check
 * requested action in lookup array
 */
if($_POST['token']==$_SESSION['token']
	&& isset($actions[$_POST['action']])) {
		$use_array = $actions[$_POST['action']];
		$obj = new $use_array['object']($dbo);
		if(TRUE === $msg=$obj->$use_array['method']()) {
			header($use_array['header']);
			exit;
		
		}else {
			// Output error if one occurred
			die($msg);		
		}
	
}else {
	// Redirect to the main index if the token or action is invalid
	header($use_array['header']);
	exit;	
}

function __autoload($class) {
	$filename = $_SERVER['DOCUMENT_ROOT']."/workout/class/class.".strtolower($class).".inc.php";
	if(file_exists($filename)) {
		include_once $filename;
	}
}
?>